
let Shader = require('../core/shader');

function buildShader(gl,vs, fs) {
    let vsShader = createShader(gl,gl.VERTEX_SHADER, vs);
    let fsShader = createShader(gl,gl.FRAGMENT_SHADER, fs);
    let program = gl.createProgram();
    gl.attachShader(program, vsShader);
    gl.attachShader(program, fsShader);
    gl.linkProgram(program);

    if (!gl.getShaderParameter(vsShader, gl.COMPILE_STATUS)) {
        let error_str = gl.getShaderInfoLog(vsShader);
        console.error('vs_shader:',error_str);
    }
    if (!gl.getShaderParameter(fsShader, gl.COMPILE_STATUS)) {
        let error_str = gl.getShaderInfoLog(fsShader);
        console.error('fs_shader:',error_str);
    }

    gl.deleteShader(vsShader);
    gl.deleteShader(fsShader);

    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        let error_str = gl.getProgramInfoLog(program);
        console.error('link_error:',error_str);
    }

    // gl.detachShader(program, vsShader);
    // gl.detachShader(program, fsShader);

    return  new Shader(gl,vsShader,fsShader,program);
}

// function createUniforms(shaderInfo, uniformNames) {
//     let gl = globalThis.app.gl;
//     uniformNames.forEach(name => {
//         let location = gl.getUniformLocation(shaderInfo.program, name);
//         if (!location) {
//             throw `getUniformLocation for ${name} failed!`;
//         }
//         shaderInfo.uniforms[name] = location;
//     });
// }
//
// function createAttribs(shaderInfo, attribs) {
//     let gl = globalThis.app.gl;
//     attribs.forEach(name => {
//         let location = gl.getAttribLocation(shaderInfo.program, name);
//         if (location < 0) {
//             throw `getAttribLocation for ${name} failed!`;
//         }
//         shaderInfo.attribs[name] = location;
//     });
// }

function createShader(gl,shaderType, source) {
    let shader = gl.createShader(shaderType);
    if (shader <= 0) {
        throw `create shaderType:${shaderType} error!`;
    }
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    let msg = gl.getShaderInfoLog(shader);
    if (msg.length > 0) {
        throw msg;
    }
    return shader;
}

module.exports = buildShader;
